<script setup>
import {
  AlarmClock as IconAlarmClock,
  Calendar as IconCalendar,
  Plus as IconPlus,
  User as IconUser
} from '@element-plus/icons-vue'
import {
  addProjectTaskApi,
  findAllWorkGroupsApi,
  findProjectTasksApi,
  findUserByNameApi
} from '@/apis/projectManagement'
import { ref, watch } from 'vue'
import router from '@/router'
import { getCurrentRouteQuery } from '@/utils/routerUtils'
import { dayjs, ElMessage } from 'element-plus'
import { onBeforeRouteUpdate } from 'vue-router'
import avatarName from '@/components/avatarName'

const filePrefix = process.env.VUE_APP_BASE_URL
const query = ref(getCurrentRouteQuery())
const projectNonStartList = ref([])
const projectStartList = ref([])
const projectCompleteList = ref([])
const projectNonCompleteList = ref([])
const addTaskDialogVisible = ref(false)
const ownerSearchLoading = ref(true)
const ownerList = ref([])
const workGroupList = ref([])

const addProjectRef = ref()
const addProjectTaskRequest = ref({
  name: null,
  projectId: null,
  owner: null,
  groupId: null,
  date: null,
  startTime: null,
  endTime: null,
  status: null,
  description: null
})

const addProjectRules = ref({
  name: [
    {
      required: true, message: '请输入项目名称', trigger: 'blur',
    }
  ],
  owner: [
    {
      required: true, message: '请选择项目负责人', trigger: 'blur',
    }
  ],
  groupId: [
    {
      required: true, message: '请选择项目所属工作组', trigger: 'blur',
    }
  ],
  description: [
    {
      required: true, message: '请输入项目描述', trigger: 'blur',
    }
  ],
  date: [
    {
      required: true, message: '请选择任务时间', trigger: 'blur',
    }
  ]
})

const onOwnerRemoteMethod = (name) => {
  ownerSearchLoading.value = true
  findUserByNameApi(name).then(({data}) => {
    ownerList.value = data || []
  }).finally(() => {
    ownerSearchLoading.value = false
  })
}

const onAddTask = (status) => {
  addProjectTaskRequest.value.projectId = query.value.id
  addProjectTaskRequest.value.status = status
  addTaskDialogVisible.value = true
}

const onSubmitTask = async (formEl) => {
  if (!formEl) return
  console.log(addProjectTaskRequest.value.date)
  await formEl.validate((valid, fields) => {
    if (valid) {
      addProjectTaskRequest.value.startTime = dayjs(addProjectTaskRequest.value.date[0]).format('YYYY-MM-DD HH:mm:ss')
      addProjectTaskRequest.value.endTime = dayjs(addProjectTaskRequest.value.date[1]).format('YYYY-MM-DD HH:mm:ss')
      addProjectTaskApi(addProjectTaskRequest.value).then(res => {
        ElMessage.success('添加成功！')
        findProjectTasksApi({projectId: query.value.id, status: 0}).then(({data}) => {
          projectNonStartList.value = data.dataList || []
        })

        // 进行中
        findProjectTasksApi({projectId: query.value.id, status: 1}).then(({data}) => {
          projectStartList.value = data.dataList || []
        })

        // 已完成
        findProjectTasksApi({projectId: query.value.id, status: 2}).then(({data}) => {
          projectCompleteList.value = data.dataList || []
        })

        // 已逾期
        findProjectTasksApi({projectId: query.value.id, status: 3}).then(({data}) => {
          projectNonCompleteList.value = data.dataList || []
        })
        addTaskDialogVisible.value = false
      })
    }
  })
}

watch(() => addTaskDialogVisible.value, (n, o) => {
  if (o) return

  findAllWorkGroupsApi().then(({data}) => {
    workGroupList.value = data || []
  })
}, {immediate: true})

// 未开始
findProjectTasksApi({projectId: query.value.id, status: 0}).then(({data}) => {
  projectNonStartList.value = data.dataList || []
})

// 进行中
findProjectTasksApi({projectId: query.value.id, status: 1}).then(({data}) => {
  projectStartList.value = data.dataList || []
})

// 已完成
findProjectTasksApi({projectId: query.value.id, status: 2}).then(({data}) => {
  projectCompleteList.value = data.dataList || []
})

// 已逾期
findProjectTasksApi({projectId: query.value.id, status: 3}).then(({data}) => {
  projectNonCompleteList.value = data.dataList || []
})

onBeforeRouteUpdate((to, from, next) => {
  query.value = to.query
  // 未开始
  findProjectTasksApi({projectId: query.value.id, status: 0}).then(({data}) => {
    projectNonStartList.value = data.dataList || []
  })

  // 进行中
  findProjectTasksApi({projectId: query.value.id, status: 1}).then(({data}) => {
    projectStartList.value = data.dataList || []
  })

  // 已完成
  findProjectTasksApi({projectId: query.value.id, status: 2}).then(({data}) => {
    projectCompleteList.value = data.dataList || []
  })

  // 已逾期
  findProjectTasksApi({projectId: query.value.id, status: 3}).then(({data}) => {
    projectNonCompleteList.value = data.dataList || []
  })

  next()
})


</script>

<template>
  <el-breadcrumb separator="/" style="margin-bottom: 36px;">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>项目任务</el-breadcrumb-item>
    <!--    <el-breadcrumb-item>{{ updateProjectDetailsRequest.name }}</el-breadcrumb-item>-->
  </el-breadcrumb>
  <div style="display: flex;">
    <div style="flex: 1; display: flex; flex-direction: column; align-items: center;">
      <div style="text-align: center; margin-bottom: 12px;">
        <span style="padding: 4px 8px; background-color: #f8a489; border-radius: 9999px; color: #fff">未开始</span>
        <span style="margin-left: 8px;">{{ projectNonStartList.length }}</span>
      </div>
      <div class="task-card-container">
        <div class="task-card-wrap" v-for="task in projectNonStartList" :key="task.id">
          <div style="display: flex; justify-content: space-between;">
            <el-tooltip placement="top">
              <template #content>{{ task.name }}</template>
              <h3 class="task-name" style="margin-bottom: 16px;">
                {{ task.name }}</h3>
            </el-tooltip>
            <el-button
                @click="router.push(`/system/projectManagement/projectTask/projectTaskDetails?taskId=${task.id}&groupId=${task.project.groupId}&name=${task.name}&projectId=${query.id}`)"
                size="small" text type="primary">详情
            </el-button>
          </div>
          <div style="margin-bottom: 12px;">
            <div style=" display: flex; align-items: center;">
              <el-icon>
                <icon-calendar />
              </el-icon>
              <span style="margin-left: 8px;">截止时间</span>
            </div>
            <div style="margin-top: 4px;">{{ task.endTime }}</div>
          </div>

          <div style="margin-bottom: 12px;">
            <div style=" display: flex; align-items: center;">
              <el-icon>
                <icon-alarm-clock />
              </el-icon>
              <span style="margin-left: 8px;">延期情况</span>
            </div>
            <div style="margin-top: 4px;">{{ task.lateDays >= 0 ? `已逾期${ task.lateDays }天` : '未逾期' }}</div>
          </div>

          <div>
            <div style="display: flex; align-items: center;">
              <el-icon>
                <icon-user />
              </el-icon>
              <span style="margin-left: 8px;">负责人</span>
            </div>
            <div style="margin-top: 4px; padding: 2px 12px 2px 6px; border-radius: 4px; background-color: #f0f1f5;">
              <avatar-name :url="task.owner.avatar ? filePrefix + task.owner.avatar : task.owner.name"
                           :name="task.owner.name" />
            </div>
          </div>
        </div>
      </div>
      <div>
        <el-button @click="onAddTask(0)" round :icon="IconPlus" style="width: 204px">添加数据</el-button>
      </div>
    </div>
    <div style="flex: 1; display: flex; flex-direction: column; align-items: center;">
      <div style="text-align: center; margin-bottom: 12px;">
        <span style="padding: 4px 8px; background-color: #3592ff; border-radius: 9999px; color: #fff">进行中</span>
        <span style="margin-left: 8px;">{{ projectStartList.length }}</span>
      </div>
      <div class="task-card-container">
        <div class="task-card-wrap" v-for="task in projectStartList" :key="task.id">
          <div style="display: flex; justify-content: space-between;">
            <el-tooltip placement="top">
              <template #content>{{ task.name }}</template>
              <h3 class="task-name" style="margin-bottom: 16px;">
                {{ task.name }}</h3>
            </el-tooltip>
            <el-button
                @click="router.push(`/system/projectManagement/projectTask/projectTaskDetails?taskId=${task.id}&groupId=${task.project.groupId}&name=${task.name}&projectId=${query.id}`)"
                size="small" text type="primary">详情
            </el-button>
          </div>
          <div style="margin-bottom: 12px;">
            <div style=" display: flex; align-items: center;">
              <el-icon>
                <icon-calendar />
              </el-icon>
              <span style="margin-left: 8px;">截止时间</span>
            </div>
            <div style="margin-top: 4px;">{{ task.endTime }}</div>
          </div>

          <div style="margin-bottom: 12px;">
            <div style=" display: flex; align-items: center;">
              <el-icon>
                <icon-alarm-clock />
              </el-icon>
              <span style="margin-left: 8px;">延期情况</span>
            </div>
            <div style="margin-top: 4px;">{{ task.lateDays >= 0 ? `已逾期${ task.lateDays }天` : '未逾期' }}</div>
          </div>

          <div>
            <div style="display: flex; align-items: center;">
              <el-icon>
                <icon-user />
              </el-icon>
              <span style="margin-left: 8px;">负责人</span>
            </div>
            <div style="margin-top: 4px; padding: 2px 12px 2px 6px; border-radius: 4px; background-color: #f0f1f5;">
              <avatar-name :url="task.owner.avatar ? filePrefix + task.owner.avatar : task.owner.name"
                           :name="task.owner.name" />
            </div>
          </div>
        </div>
      </div>
      <div>
        <el-button @click="onAddTask(1)" round :icon="IconPlus" style="width: 204px">添加数据</el-button>
      </div>
    </div>
    <div style="flex: 1; display: flex; flex-direction: column; align-items: center;">
      <div style="text-align: center; margin-bottom: 12px;">
        <span style="padding: 4px 8px; background-color: #32c66e; border-radius: 9999px; color: #fff">已完成</span>
        <span style="margin-left: 8px;">{{ projectCompleteList.length }}</span>
      </div>
      <div class="task-card-container">
        <div class="task-card-wrap" v-for="task in projectCompleteList" :key="task.id">
          <div style="display: flex; justify-content: space-between;">
            <el-tooltip placement="top">
              <template #content>{{ task.name }}</template>
              <h3 class="task-name" style="margin-bottom: 16px;">
                {{ task.name }}</h3>
            </el-tooltip>
            <el-button
                @click="router.push(`/system/projectManagement/projectTask/projectTaskDetails?taskId=${task.id}&groupId=${task.project.groupId}&name=${task.name}&projectId=${query.id}`)"
                size="small" text type="primary">详情
            </el-button>
          </div>
          <div style="margin-bottom: 12px;">
            <div style=" display: flex; align-items: center;">
              <el-icon>
                <icon-calendar />
              </el-icon>
              <span style="margin-left: 8px;">截止时间</span>
            </div>
            <div style="margin-top: 4px;">{{ task.endTime }}</div>
          </div>

          <div style="margin-bottom: 12px;">
            <div style=" display: flex; align-items: center;">
              <el-icon>
                <icon-alarm-clock />
              </el-icon>
              <span style="margin-left: 8px;">延期情况</span>
            </div>
            <div style="margin-top: 4px;">{{ task.lateDays >= 0 ? `已逾期${ task.lateDays }天` : '未逾期' }}</div>
          </div>

          <div>
            <div style="display: flex; align-items: center;">
              <el-icon>
                <icon-user />
              </el-icon>
              <span style="margin-left: 8px;">负责人</span>
            </div>
            <div style="margin-top: 4px; padding: 2px 12px 2px 6px; border-radius: 4px; background-color: #f0f1f5;">
              <avatar-name :url="task.owner.avatar ? filePrefix + task.owner.avatar : task.owner.name"
                           :name="task.owner.name" />
            </div>
          </div>
        </div>
      </div>
      <div>
        <el-button @click="onAddTask(2)" round :icon="IconPlus" style="width: 204px">添加数据</el-button>
      </div>
    </div>
    <div style="flex: 1; display: flex; flex-direction: column; align-items: center;">
      <div style="text-align: center; margin-bottom: 12px;">
        <span style="padding: 4px 8px; background-color: #f56c6c; border-radius: 9999px; color: #fff">已逾期</span>
        <span style="margin-left: 8px;">{{ projectNonCompleteList.length }}</span>
      </div>
      <div class="task-card-container">
        <div class="task-card-wrap" v-for="task in projectNonCompleteList" :key="task.id">
          <div style="display: flex; justify-content: space-between;">
            <el-tooltip placement="top">
              <template #content>{{ task.name }}</template>
              <h3 class="task-name" style="margin-bottom: 16px;">
                {{ task.name }}</h3>
            </el-tooltip>
            <el-button
                @click="router.push(`/system/projectManagement/projectTask/projectTaskDetails?taskId=${task.id}&groupId=${task.project.groupId}&name=${task.name}&projectId=${query.id}`)"
                size="small" text type="primary">详情
            </el-button>
          </div>
          <div style="margin-bottom: 12px;">
            <div style=" display: flex; align-items: center;">
              <el-icon>
                <icon-calendar />
              </el-icon>
              <span style="margin-left: 8px;">截止时间</span>
            </div>
            <div style="margin-top: 4px;">{{ task.endTime }}</div>
          </div>

          <div style="margin-bottom: 12px;">
            <div style=" display: flex; align-items: center;">
              <el-icon>
                <icon-alarm-clock />
              </el-icon>
              <span style="margin-left: 8px;">延期情况</span>
            </div>
            <div style="margin-top: 4px;">{{ task.lateDays >= 0 ? `已逾期${ task.lateDays }天` : '未逾期' }}</div>
          </div>

          <div>
            <div style="display: flex; align-items: center;">
              <el-icon>
                <icon-user />
              </el-icon>
              <span style="margin-left: 8px;">负责人</span>
            </div>
            <div style="margin-top: 4px; padding: 2px 12px 2px 6px; border-radius: 4px; background-color: #f0f1f5;">
              <avatar-name :url="task.owner.avatar ? filePrefix + task.owner.avatar : task.owner.name"
                           :name="task.owner.name" />
            </div>
          </div>
        </div>
      </div>
      <div>
        <el-button @click="onAddTask(3)" round :icon="IconPlus" style="width: 204px">添加数据</el-button>
      </div>
    </div>
  </div>
  <el-dialog v-model="addTaskDialogVisible"
             title="添加任务"
             draggable
             overflow
             width="700px">
    <el-form ref="addProjectRef" inline :rules="addProjectRules" :model="addProjectTaskRequest" label-position="top">
      <el-form-item label="任务名称" prop="name">
        <el-input style="width: 660px;" v-model="addProjectTaskRequest.name" placeholder="输入任务名称"></el-input>
      </el-form-item>

      <el-form-item label="任务负责人" prop="owner">
        <el-select
            v-model="addProjectTaskRequest.owner"
            :remote-method="onOwnerRemoteMethod"
            placeholder="搜索负责人"
            :loading="ownerSearchLoading"
            style="width: 200px"
            clearable
            filterable
            remote
        >
          <el-option
              v-for="owner in ownerList"
              :key="owner.id"
              :label="owner.name"
              :value="owner.id"
          >
            <span style="float: left">{{ owner.name }}</span>
            <span
                style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">
                {{ owner.username }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="任务所属工作组" prop="groupId">
        <el-select
            v-model="addProjectTaskRequest.groupId"
            placeholder="选择项目所属工作组"
            style="width: 200px"
            clearable
        >
          <el-option v-for="group in workGroupList" :key="group.id" :label="group.gName" :value="group.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="status" style="margin-right: 0">
        <el-select
            v-model="addProjectTaskRequest.status"
            style="width: 194px"
            disabled
        >
          <el-option label="未开始" :value="0" />
          <el-option label="进行中" :value="1" />
          <el-option label="已完成" :value="2" />
          <el-option label="已逾期" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务时间" prop="date">
        <el-date-picker
            style="width: 638px;"
            v-model="addProjectTaskRequest.date"
            type="datetimerange"
            range-separator="-"
            start-placeholder="任务开始时间"
            end-placeholder="任务预计结束时间"
        />
      </el-form-item>

      <el-form-item label="任务描述" prop="description">
        <el-input style="width: 660px;" v-model="addProjectTaskRequest.description" type="textarea" :rows="4"
                  placeholder="描述下任务吧"></el-input>
        <!--        <el-input v-model="form.name" autocomplete="off"/>-->
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" size="small" @click="addTaskDialogVisible = false">取消</el-button>
        <el-button type="primary" size="small" @click="onSubmitTask(addProjectRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="less">
.task-card-container {
  overflow: scroll;
  max-height: 70vh;

  &::-webkit-scrollbar {
    width: 4px;
    height: 4px;
  }
}

.task-card-wrap {
  width: 180px;
  padding: 12px 12px 16px;
  margin: 12px 4px 12px;
  border-radius: 6px;
  background-color: #fff;
  box-shadow: 0 0 6px rgba(0, 0, 0, .12);
  transition: box-shadow 0.3s;

  &:hover {
    box-shadow: 0 0 12px rgba(0, 0, 0, .12)
  }

  .task-name {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

:deep(.el-textarea__inner) {
  resize: none;
}
</style>